/**
 * 上传用户头像
 */
import { Button, Modal, Upload ,message } from 'antd';
import React, { useState } from 'react';
import ImgCrop from 'antd-img-crop';
import axios from 'axios'


//创建axios请求头
let config = {headers:{'Content-Type':'multipart-/form-data',withCredentials:true}}

const HeardImage = (props) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  //定义路由变量
  //头像
  const [fileList, setFileList] = useState([]);
  const onHeardChange = async ({ fileList: newFileList }) => {
    //获取条目id
    setFileList(newFileList);
    //请求后台进行进行数据的修改
    axios({
      method:'post',
      cache:false,
      url:'http://localhost/mall-basic-service/basic/user/updateUser',
      params:{
        userid: props.getUser[0].userid,
        headPortraitUrl: newFileList[0].response,
        imgName:newFileList[0].name
      }
    },config).then((response)=>{
      // 刷新操作
      if(response.data.code===200){
        window.location.reload()
      }
    })
  };
  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  /**
   * 点击上传按钮时触发
   */
  const showModal = () => {
    if(props.getUser.length === 1){
      setIsModalOpen(true);
      const news = [{
        uid: props.getUser[0].userid,
        name: props.getUser[0].username,
        status: 'done',
        url: props.getUser[0].headPortraitUrl,
      }]
      setFileList(news);
    }else{
      if(props.getUser.length > 1){
        message.warning('只能选一项');
      }else if(props.getUser.length === 0 ){
        message.warning('请选择条目');
      }
    }
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div className={'addButDiv'}>
      <Button onClick={showModal}>
        上传头像
      </Button>
      <Modal title="上传头像" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <ImgCrop rotate>
          <Upload
            action="http://localhost/mall-basic-service/util/upload/importPicture"
            listType="picture"
            fileList={fileList}
            onChange={onHeardChange}
            onPreview={onPreview}
            maxCount={1}
          >
            {fileList.length < 2 && '+ Upload'}
          </Upload>
        </ImgCrop>
      </Modal>
    </div>
  );
};
export default HeardImage;
